package com.h5lib.xlsx4j;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.*;

public class XMLSharedStringReader {

    private XmlPullParser inputStream;

    public XMLSharedStringReader(XmlPullParser newPullParser) {
        inputStream = newPullParser;
    }

    public String next() throws XmlPullParserException, IOException {

        StringBuilder tagContent = new StringBuilder();

        int si = 0;
        boolean inT = false;
        int event = inputStream.getEventType();
        while ((event) != XmlPullParser.END_DOCUMENT  && si >= 0) {
            String name = inputStream.getName();
			switch (event) {
                case XmlPullParser.START_TAG:
                    if ("si".equals(name)) {
                        si++;
                    }

                    if ("t".equals(name) && si > 0) {
                        inT = true;
                    }
                    break;

                case XmlPullParser.END_TAG:
                    inT = false;
                    if ("si".equals(name)) {
                        si -= (si > 1) ? 1 : 2;
                    }
                    break;

                case XmlPullParser.TEXT:
                    if (inT) {
                        tagContent.append(inputStream.getText().trim());
                    }
                    break;
            }
			event = inputStream.next();
        }

        return si < 0 ? tagContent.toString() : null;
    }

    public List<String> fetchAll() throws XmlPullParserException, IOException {

        List<String> sharedStrings = new ArrayList<String>();

        String entry;
        while ((entry = next()) != null) {
            sharedStrings.add(entry);
        }

        return sharedStrings;
    }
}
